<template>
  <div>
    <div class="supplier" v-if="!materialClassAddShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:materialClass:query']"
          v-preventReClick
          class="btn search"
          @click="getMaterialClassList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button
          v-hasPermi="['system:materialClass:add']"
          v-preventReClick
          class="btn search"
          @click="
            materialClassAddShow = true;
            pageType = 'add';
          "
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <!-- <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        > -->
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="name">分类名称</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <!-- <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model="params.name"
            class="search-input"
            maxlength="30"
            placeholder="请输入分类名称"
          ></el-input>
        </div>
      </div> -->
      <!-- 表格数据 -->
      <el-table
        row-key="id"
        :default-expand-all="true"
        v-loading="loading"
        :data="materialClassList"
        border
        height="70vh"
        :header-cell-style="{ 'text-align': 'center', background: 'red' }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        /> -->
        <el-table-column v-if="checkList.includes('name')"
          label="分类名称"
          prop="name"
          :show-overflow-tooltip="true"
          min-width="80"
        >
          <template #default="{ row }">
            <span>{{ row.categoryName }}</span>
            <el-icon
              v-if="row.importantDevice == 1"
              style="margin-left: 5px; transform: translateY(4px)"
              title="贵重设备"
              color="#FF9552"
              :size="20"
            >
              <Box />
            </el-icon>
          </template>
        </el-table-column>
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          width="140px"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                title="新增子分类"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('add', row)"
                v-hasPermi="['system:materialClass:addSon']"
                v-if="row.childCategory == 1"
              >
                <DocumentAdd />
              </el-icon>
              <el-icon
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
                v-hasPermi="['system:materialClass:edit']"
                v-if="row.categoryId != 0"
              >
                <Edit />
              </el-icon>
              <el-icon
                v-if="!row.children"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
                v-hasPermi="['system:materialClass:remove']"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getMaterialClassList"
      />
    </div>
    <SupplierAdd
      v-if="materialClassAddShow"
      ref="materialClassAddRef"
      v-model:materialClassAddShow="materialClassAddShow"
      @refreshList="getMaterialClassList"
      :pageType="pageType"
      :materialClassList="screenlist"
    />
  </div>
</template>

<script setup>
import SupplierAdd from "./materialClassAdd";
const { proxy } = getCurrentInstance();
import {
  getMaterialClassListApi,
  deleteMaterialClassApi,
} from "@/api/information/materialClass";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 搜索参数
const params = reactive({
  name: "",
  pageNum: 1,
  pageSize: 50,
});

const checkList = ref([
  "name",
]);


// 表格加载效果
const loading = ref(false);
// 物料分类新增组件显隐
const materialClassAddShow = ref(false);
// 物料分类列表
const materialClassList = ref([]);
// 总数
const total = ref(0);
// 物料分类新增组件引用
const materialClassAddRef = ref(null);
// 操作类型
const pageType = ref("");


/**
 * @description: 复选框选中
 */
 const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 3,
    titleField: str,
  });
  // getTableHeader();
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 3,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
 const handleRefresh = () => {
  Object.assign(params, {
    name: "",
    pageNum: 1,
    pageSize: 50,
  });
  getMaterialClassList()
};

/**
 * @description: 获取物料分类列表
 */
let screenlist = [];
const getMaterialClassList = async () => {
  try {
    loading.value = true;
    let { name, pageNum, pageSize } = params;
    const res = await getMaterialClassListApi(
      { pageNum, pageSize },
      {
        name,
      }
    );
    let obj = [
      {
        categoryId: 0,
        categoryName: "全部",
        parentId: null,
        children: [],
        id: 0,
      },
    ];
    res.rows.forEach((item) => {
      item.id = item.categoryId;
    });
    screenlist = res.rows;
    let treeData = proxy.handleTree(res.rows, "id");
    obj[0].children.push(...treeData);
    materialClassList.value = obj;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "add":
      materialClassAddShow.value = true;
      pageType.value = "add";
      nextTick(() => {
        materialClassAddRef.value.handleParentId(row.categoryId);
      });
      break;
    case "edit":
      materialClassAddShow.value = true;
      pageType.value = "edit";
      nextTick(() => {
        materialClassAddRef.value.handleDetailInfo(row);
      });
      break;
    case "delete":
      ElMessageBox.confirm("此操作将删除该分类，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteMaterialClassApi(row.categoryId);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getMaterialClassList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  getMaterialClassList();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.supplier {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
}
</style>
